<?php

namespace Apps\AppApi\Method\Order;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\Pay;
use Apps\Common\Models\BeautyParlorService;
use Apps\Common\Models\UserOrder;
use Apps\Common\Models\UserOrderGoods;
use PhalconPlus\Api\Common\ResultStatus;
use PhalconPlus\Common\Util;

/**
 * 添加新订单
 * @package Apps\Apps\AppApi\Method\Order
 */
class OrderAdd extends BaseMethod
{
    public function run()
    {
        /**
         * 验证用户权限
         */
        if(false == $this->verifyUserAuth()){
            return false;
        }
        $mobile = $this->getDataItem('mobile');
        $payType = $this->getDataItem('pay_type');
        $goods = $this->getDataItem('goods');
        if(empty($mobile) || empty($payType) || empty($goods) || !is_array($goods) || count($goods) == 0) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR);
        }
        $payTypeValue = $this->getPayTypeNum($payType);
        if($payTypeValue <= 0) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '支付方式不支持.');
        }
        $userId = $this->getUserAuth()->userId;
        $goodsInfo = $this->getGoodsInfo($goods);
        if(count($goodsInfo) == 0) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '商品内容为空.');
        }
        // 计算总价格
        $money = 0;
        foreach($goodsInfo as $gi) {
            $money = $money + $gi['order_number'] * $gi['service_price'];
        }
        $longId = Util::LongId(true);
        $orderId = $this->addOrderBase($longId, $mobile, $payTypeValue, $money, $userId);
        if($orderId == 0) {
            return;
        }
        foreach($goodsInfo as $gi) {
            $ogid = $this->addOrderGoods($userId, $orderId, $gi);
            if($ogid <= 0) {
                UserOrder::SetOrderState($userId, $orderId, -1);
                return;
            }
        }
        $weixinPay = null;
        // 判断是否微信支付，微信支付需去下单
        if($payTypeValue == 1) {
            $pay = new Pay();
            $weixinPay = $pay->weiXin2AppPay($orderId);
        }
        $this->setResult([
            'success' => 1,
            'order_id' => $orderId,
            'order_long_id' => $longId,
            'weixin_pay' => $weixinPay ? $weixinPay : null,
        ]);
    }

    /**
     * 添加订单基础信息
     * @param $longId
     * @param $mobile
     * @param $payType
     * @param $money
     * @param $userId
     * @return int
     */
    private function addOrderBase($longId, $mobile, $payType, $money, $userId)
    {
        $order = new UserOrder();
        $order->order_long_id = $longId;
        $order->order_type = 1;
        $order->user_id = $userId;
        $order->order_mobile = $mobile;
        $order->order_origin = 1;
        $order->order_money = $money;
        $order->order_freight = 0;
        $order->order_remake = '';
        $order->order_pay_type = $payType;
        if($order->save()) {
            return $order->order_id;
        } else {
            $this->databaseErrorLog($order);
            return 0;
        }
    }

    /**
     * 获取商品信息
     * @param $goods
     * @return array
     */
    private function getGoodsInfo($goods)
    {
        $goodsList = [];
        foreach($goods as $g) {
            $id = isset($g['id']) ? intval($g['id']) : 0;
            $num = isset($g['number']) ? intval($g['number']) : 0;
            if($id <= 0 || $num <= 0) {
                continue;
            }
            $info = BeautyParlorService::findFirst("service_id = $id AND service_state > 0 AND service_is_sell = 1");
            if($info) {
                $gi = [
                    'service_id' => $info->service_id,
                    'beauty_parlor_id' => $info->beauty_parlor_id,
                    'service_price' => $info->service_price,
                    'order_number' => $num,
                ];
                $goodsList[] = $gi;
            }
        }
        return $goodsList;
    }

    /**
     * 添加订单中的商品
     * @param $userId
     * @param $orderId
     * @param $goodsInfo
     * @return int
     */
    private function addOrderGoods($userId, $orderId, $goodsInfo)
    {
        $orderGoods = new UserOrderGoods();
        $orderGoods->order_id = $orderId;
        $orderGoods->user_id = $userId;
        $orderGoods->shop_id = $goodsInfo['beauty_parlor_id'];
        $orderGoods->goods_id = $goodsInfo['service_id'];
        $orderGoods->goods_style_id = 0;
        $orderGoods->order_goods_number = $goodsInfo['order_number'];
        $orderGoods->goods_price = $goodsInfo['service_price'];
        $orderGoods->order_goods_state = 1;
        if($orderGoods->save()) {
            return $orderGoods->order_goods_id;
        } else {
            $this->databaseErrorLog($orderGoods);
            return 0;
        }
    }
}